import backtrader as bt
import numpy as np
import pandas as pd
class IndicatorTest(bt.Indicator):
    lines = ('test',)

    params = (
        ('N1', 5),
        ('N2', 20),
        ('N3', 25)
    )

    def __init__(self, test_window,data):
        self.vdata = data
        #self.test = data.get(ago=data.buflen(), size=data.buflen())
        self.params.test_window = test_window
        # 这个很有用，会有 not maturity生成
        self.addminperiod(self.params.test_window*2)



    def test1(self,value_list):
        #value_list = input_array.close.get(ago=self.buflen(), size=self.buflen())  # 从头取到尾
        stockdata = pd.DataFrame(value_list, columns=['close'])
        df_close = stockdata.close / stockdata.close[0]  # 计算净值
        wave = []
        for i in range(0, len(stockdata.index)):  # 计算20天的波动率
            if i > 20:
                wave.append(np.std(np.log(df_close[i - 20:i] / df_close[i - 20:i].shift(-1))) * np.sqrt(252) * 100)
            else:
                wave.append(0)
        #window_matrix = self.get_window_matrix(input_array, t, m)
        #new_matrix = self.svd_reduce(window_matrix)
        #new_array = self.recreate_array(new_matrix, t, m)
        print(wave[-1])
        return wave[-1]

    def next(self):
        value_list = self.vdata.get(size=self.params.test_window)  # 从头取到尾
        #stockdata = pd.DataFrame(value_list, columns=['close'])
        #data_serial = self.data.get(size=self.params.test_window)
        #stockdata = pd.DataFrame(data_serial, columns=['close'])
        print(self.lines.test )
        self.lines.test[0] = self.test1(value_list)
        print(self.lines.test[0])